﻿/*
Copyright © 2011 Nokia Corporation. All rights reserved.
Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
Java and all Java-based marks are trademarks or registered trademarks of 
Sun Microsystems, Inc. Other product and company names mentioned herein may be 
trademarks or trade names of their respective owners.

Subject to the conditions below, you may, without charge:

·  Use, copy, modify and/or merge copies of this software and 
   associated content and documentation files (the “Software”)

·  Publish, distribute, sub-licence and/or sell new software 
   derived from or incorporating the Software.

Some of the documentation, content and/or software maybe licensed under open source software or other licenses.  To the extent such documentation, content and/or software are included, licenses and/or other terms and conditions shall apply in addition and/or instead of this notice. The exact terms of the licenses, disclaimers, acknowledgements and notices are reproduced in the materials provided.

This file, unmodified, shall be included with all copies or substantial portions
of the Software that are distributed in source code form.

The Software cannot constitute the primary value of any new software derived 
from or incorporating the Software.

Any person dealing with the Software shall not misrepresent the source of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Carpool.Bing.Route;
using System.Globalization;
using Microsoft.Phone.Controls.Maps.Platform;
using Microsoft.Phone.Tasks;

namespace Carpool
{
    public partial class JoinConfirmation : UserControl
    {

        DCRoute route;

        double picklatitude = 0;
        double picklongitude = 0;
        double distancefromstart = 0;
        long traveltimefromstart = 0;

        public JoinConfirmation()
        {
            InitializeComponent();
        }

        internal void setInfo(DCRoute _route)
        {
            route = _route;

            routename.Text = route.name;
            routedescription.Text = route.description;
            routefrom.Text = route.route[0].street + ", " + route.route[0].city;
            routeto.Text = route.route[1].street + ", " + route.route[1].city;
            routedistance.Text = route.route[1].distance.ToString() + " km";
            routetraveltime.Text = MainPage.main.routetool.secondToHMS(route.route[1].traveltime);
            string ownerinfo = "";
            if (route.showownername.CompareTo("1") == 0)
                ownerinfo = route.ownerinfo.firstname + " " + route.ownerinfo.lastname + " ";
            if (route.showownerphone.CompareTo("1") == 0)
                ownerinfo += route.ownerinfo.phone + " ";
            if (route.showownerhometown.CompareTo("1") == 0)
                ownerinfo += route.ownerinfo.hometown;

            routeowner.Text = ownerinfo;

            joinconfirmationPopup.IsOpen = true;
        }

        private void joinconfirmationGrid_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            joinconfirmationTranslateTransform.X += e.DeltaManipulation.Translation.X;
            joinconfirmationTranslateTransform.Y += e.DeltaManipulation.Translation.Y;
        }

        private void picklocationButton_Click(object sender, RoutedEventArgs e)
        {
            joinconfirmationPopup.IsOpen = false;
            MainPage.main.showCrosshair(true);
        }

        private void sendrequestButton_Click(object sender, RoutedEventArgs e)
        {
            requesttextbox.Text = "I'd like to join your route '" + route.name + "'.";
            joinconfirmationPopup.IsOpen = false;
            requestsendingPopup.IsOpen = true;
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            joinconfirmationPopup.IsOpen = false;
            MainPage.main.jointrip.JoinTripRoutes.Visibility = Visibility.Visible;
        }


        internal void setPickLocation(double lat, double lon)
        {
            picklatitude = lat;
            picklongitude = lon;

            joinconfirmationPopup.IsOpen = true;

            MainPage.main.routetool.showPickPin(lat, lon);

            picklocation.Text = picklatitude.ToString() + ", " + picklongitude.ToString();

            CalculateRouteLatLon(route.route[0].latitude, route.route[0].longitude, lat, lon);
        }


        internal void CalculateRouteLatLon(double latFrom, double lonFrom, double latTo, double lonTo)
        {
            KarpoMessageBox.showMessageBox("Calculating the distance from start ...");

            RouteServiceClient client = new RouteServiceClient();
            client.CalculateRouteCompleted += new EventHandler<CalculateRouteCompletedEventArgs>(client_CalculateRouteLatLonCompleted);

            RouteRequest request = new RouteRequest();

            request.Culture = CultureInfo.CurrentUICulture.Name;

            // Don't raise exceptions.
            request.ExecutionOptions = new Carpool.Bing.Route.ExecutionOptions()
            {
                SuppressFaults = true
            };

            // Only accept results with high confidence.
            request.Options = new RouteOptions()
            {
                RoutePathType = RoutePathType.Points
            };

            Waypoint fromWaypoint = new Waypoint();
            fromWaypoint.Location = new Location();
            fromWaypoint.Location.Latitude = latFrom;
            fromWaypoint.Location.Longitude = lonFrom;

            Waypoint toWaypoint = new Waypoint();
            toWaypoint.Location = new Location();
            toWaypoint.Location.Latitude = latTo;
            toWaypoint.Location.Longitude = lonTo;

            request.Waypoints = new System.Collections.ObjectModel.ObservableCollection<Waypoint>();
            request.Waypoints.Add(fromWaypoint);
            request.Waypoints.Add(toWaypoint);

            MainPage.main.KarpoCredentialsProvider.GetCredentials(credentials =>
            {
                // Pass in credentials for web services call.
                request.Credentials = credentials;

                // Make asynchronous call to fetch the data.
                client.CalculateRouteAsync(request);

            });


        }



        void client_CalculateRouteLatLonCompleted(object sender, CalculateRouteCompletedEventArgs e)
        {
            KarpoMessageBox.hideMessageBox();

            if (e.Result.ResponseSummary.StatusCode == Bing.Route.ResponseStatusCode.Success)
            {

                distancefromstart = e.Result.Result.Summary.Distance;
                traveltimefromstart = e.Result.Result.Summary.TimeInSeconds;

                fromstart.Text = distancefromstart.ToString() + " km, " + MainPage.main.routetool.secondToHMS(traveltimefromstart);

            }
            else
            {
                // Report route error.
                KarpoMessageBox.showMessageBox("client_CalculateRouteLatLonCompleted error: " + MapError.Reason(e));

            }
        }

        // ================  REQUEST SENDING POPUP   ================

        private void requestsendingGrid_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            requestsendingTranslateTransform.X += e.DeltaManipulation.Translation.X;
            requestsendingTranslateTransform.Y += e.DeltaManipulation.Translation.Y;
        }

        private void cancelsendButton_Click(object sender, RoutedEventArgs e)
        {
            requestsendingPopup.IsOpen = false;
            joinconfirmationPopup.IsOpen = true;
        }

        private void sendButton_Click(object sender, RoutedEventArgs e)
        {
            KarpoMessageBox.showMessageBox("Saving the joinrequest ...");

            if (string.IsNullOrEmpty(route.ownerinfo.phone))
            {
                KarpoMessageBox.showMessageBox("The phonenumber of the route's owner is unknown. Can't send the request.");
            }
            else
            {

                DCJoinRequest joinreq = new DCJoinRequest();
                joinreq.joinrequestkarpoid = "0"; // this is set in the KarpoDC servlet and used when sending the sms
                joinreq.carpoolkarpoid = route.carpoolkarpoid;
                joinreq.routekarpoid = route.routekarpoid;
                joinreq.ownerkarpoid = route.ownerkarpoid;
                joinreq.travellerkarpoid = MainPage.userkarpoid;
                joinreq.showname = ((bool)shownamecheckbox.IsChecked ? "1" : "0");
                joinreq.showhometown = ((bool)showhometowncheckbox.IsChecked ? "1" : "0");
                joinreq.showphone = ((bool)showphonecheckbox.IsChecked ? "1" : "0");
                joinreq.message = requesttextbox.Text;
                joinreq.picklat = picklatitude;
                joinreq.picklon = picklongitude;

                DC.DataCloud().SaveJoinRequest(joinreq, savejoinrequestcb);
            }
        }

        internal void savejoinrequestcb(bool isok, string errormsg, DCJoinRequest joinreq)
        {
            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (joinreq.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + joinreq.errorString);
            }
            else
            {
                KarpoMessageBox.hideMessageBox();

                // Next send the joinrequest sms ...

                KarpoMessageBox.showMessageBox("Send the joinrequest to " + route.ownerinfo.phone);

                SmsComposeTask smsComposeTask = new SmsComposeTask();
                smsComposeTask.To = route.ownerinfo.phone;
                smsComposeTask.Body = "You have a joinrequest. See the link " + MainPage.datacloudurl + "/Membership?joinrequestid=" + joinreq.joinrequestkarpoid;


                RestoreUI rui = new RestoreUI("joinrequest");

                (Application.Current as Carpool.App).restoreui = rui;

                smsComposeTask.Show();

            }
        }
    }
}
